package com.wish.protobuf;

import com.google.protobuf.InvalidProtocolBufferException;

/**
 * @author tantexian
 * @since 2016/7/12
 */
public class UserSerializableTest {

    public static void main(String[] args) {
        ProtobufUser.User user = createUser();
        System.out.println("Before encode: \n" + user);
        byte[] encodeBytes = encode(user);
        System.out.println("After encode: \n" + encodeBytes);
        ProtobufUser.User userByDecode = decode(encodeBytes);
        System.out.println("After decode: \n" + userByDecode);
    }

    private static byte[] encode(ProtobufUser.User User){
        return User.toByteArray();
    }

    private static ProtobufUser.User decode(byte[] byteBody) {
        try {
            return ProtobufUser.User.parseFrom(byteBody);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static ProtobufUser.User createUser(){
        ProtobufUser.User.Builder builder = ProtobufUser.User.newBuilder();
        builder.setId(1);
        builder.setUserName("tantexian");
        builder.setAddress("sichuan,chengdu!");
        return builder.build();
    }
}
